<template>
  <el-container>
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" label-width="100px">
        <el-form-item label="所属上级" prop="pid">
          <el-cascader
            v-model="form.model.pid"
            :options="area.select"
            :props="{
              label: 'name',
              value: 'id',
              checkStrictly: true,
              emitPath: false,
            }"
            clearable
            placeholder="请选择上级行政区"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="行政区ID" prop="id">
          <el-input v-model="form.model.id" placeholder="请输入行政区ID"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.model.name" placeholder="请输入名称"></el-input>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button
        v-if="modal.params.type == 'add'"
        v-auth="'shop.admin.data.area.add'"
        type="primary"
        @click="confirm"
        >保存</el-button
      >
      <el-button
        v-if="modal.params.type == 'edit'"
        v-auth="'shop.admin.data.area.edit'"
        type="primary"
        @click="confirm"
        >更新</el-button
      >
    </el-footer>
  </el-container>
</template>
<script setup>
  import { onMounted, reactive, ref, unref } from 'vue';
  import { api } from '../data.service';
  import { cloneDeep } from 'lodash';

  const emit = defineEmits(['modalCallBack']);
  const props = defineProps({
    modal: {
      type: Object,
    },
  });
  // 添加 编辑 form
  let formRef = ref(null);
  const form = reactive({
    model: {
      id: '',
      name: '',
      pid: 0,
    },
    rules: {
      name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      id: [{ required: true, message: '请输入行政区ID', trigger: 'blur' }],
    },
  });
  const loading = ref(false);
  const area = reactive({
    select: [],
  });
  async function getAreaSelect() {
    ({ data: area.select } = await api.area.select({
      level: 'city',
    }));
  }
  // 获取详情
  async function getDetail(id) {
    loading.value = true;
    const { error, data } = await api.area.detail(id);
    error === 0 && (form.model = data);
    loading.value = false;
  }
  // 表单关闭时提交
  async function confirm() {
    // 表单验证
    unref(formRef).validate(async (valid) => {
      if (!valid) return;
      let submitForm = cloneDeep(form.model);
      const { error } =
        props.modal.params.type == 'add'
          ? await api.area.add(submitForm)
          : await api.area.edit(props.modal.params.id, submitForm);
      if (error == 0) {
        emit('modalCallBack', { event: 'confirm' });
      }
    });
  }
  async function init() {
    await getAreaSelect();
    if (props.modal.params.id) {
      await getDetail(props.modal.params.id);
    }
  }
  onMounted(() => {
    init();
  });
</script>
